/**
 * Created by XianTao on 2015/1/26
 *
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package com.taotao.wechat.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.database.domain.WechatUser;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.message.resp.BaseMessage;
import com.taotao.wechat.message.resp.TextMessage;
import com.taotao.wechat.util.MessageUtil;
import com.taotao.wechat.util.ValidateUtil;
import org.apache.commons.lang.StringUtils;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

/**
 * 呼伦贝尔 -- 关注送流量
 * 时间：2015年2月14日-3月31日--6月30日
 * 规则：
 * 活动期间，用户通过扫描二维码等方式关注移动微信平台，可获得一次参与流量红包活动的抽奖机会，
 * 流量于每月28日前赠送，次月31日失效
 */
public class FirstFocusGame1 extends Game {
    public static final boolean IS_ENABLE = true;
    /**老用户返回的提示消息*/
    protected String msgWhenOldUser = "您好，活动" + getName() + "只有新用户才可以参加~";

    public FirstFocusGame1() {
    }

    public FirstFocusGame1(BaseMessage baseMessage, String content, String appKey) {
        super(baseMessage, content, appKey);
    }

    private Object[][] prizeArray = new Object[][]{
            //id, prizeInfo, prize, rate
            {1, "恭喜您，获得1G流量，流量将于次月上账", "1G流量", 1},
            {2, "恭喜您，获得500M流量，流量将于次月上账", "500M流量", 4},
            {3, "恭喜您，获得200M流量，流量将于次月上账", "200M流量", 45},
            {4, "恭喜您，获得100M流量，流量将于次月上账", "100M流量", 450},
            {5, "恭喜您，获得50M流量，流量将于次月上账", "50M流量", 1500},
            {6, "恭喜您，获得30M流量，流量将于次月上账", "30M流量", 8000},
            {0, "谢谢参与~~", "谢谢参与", 0}
    };

    /**
     * 根据概率获取中奖项的下标
     */
    private synchronized Integer getAwardIndex(Object[][] prizeArr, int rateIndex) {
        //概率数组
        Integer obj[] = new Integer[prizeArr.length];
        for (int i = 0; i < prizeArr.length; i++) {
            obj[i] = (Integer) prizeArr[i][rateIndex];
        }

        //默认未中奖
        Integer result = prizeArr.length - 1;
        try {
            int sum = 0;//概率数组的总概率精度
            for (Integer anObj : obj) {
                sum += anObj;
            }
            for (int i = 0; i < obj.length; i++) {//概率数组循环
                int randomNum = new Random().nextInt(sum);//随机生成1到sum的整数
                if (randomNum < obj[i]) { //中奖
                    result = i;
                    break;
                } else {
                    sum -= obj[i];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //这里返回的是随机奖励
    @Override
    protected String gameUrl() {
        TextMessage textMessage = new TextMessage(baseMessage);
        //判断是否已经中奖
        PlayGame condition = new PlayGame();
        condition.setAppId(appKey);
        condition.setOpenId(baseMessage.getToUserName());
        condition.setTel(content);
        condition.setGameName(getNickName());
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getMyPrizes", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (respData != null && respData.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("恭喜您在").append(getName()).append("活动中，");
                    for (LinkedHashMap<String, Object> map : respData) {
                        sb.append("手机号码");
                        sb.append(map.get("tel").toString()).append("获得")
                                .append(map.get("result").toString()).append("，");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    textMessage.setContent(sb.toString());
                    return MessageUtil.textMessageToXml(textMessage);
                }
            }
        }

        //判断是否是新用户
        if (!isNewUser(baseMessage.getToUserName(), appKey)) {
            textMessage.setContent(msgWhenOldUser);
            return MessageUtil.textMessageToXml(textMessage);
        }

        //抽奖
        Object[] prizeArray = this.prizeArray[getAwardIndex(this.prizeArray, 3)];
        String prize = prizeArray[0].toString();
        String result = prizeArray[2].toString();
        //save into database
        endGame(appKey, baseMessage.getToUserName(), getNickName(), content, result, prize);
        textMessage.setContent(prizeArray[1].toString());
        return MessageUtil.textMessageToXml(textMessage);
    }

    @Override
    public String getAppIds() {
        return "wx13c16cf4b3039116";
    }

    @Override
    protected String inputTelephone() {
        //判断属于哪款游戏
        String currentGameName = getLatestInputGameName(baseMessage.getToUserName(), appKey);
        if (StringUtils.isBlank(currentGameName) || !currentGameName.equalsIgnoreCase(getNickName())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //判断是否是内蒙移动手机号
            int telType = ValidateUtil.isYiDong(content, "呼伦贝尔");
            if (telType != 0) {
                if (telType == -1) {
                    textMessage.setContent(getMsgTelNotKnow());
                } else if (telType == 1) {
                    textMessage.setContent(getMsgTelNotNeiMengCMCC());
                } else if (telType == -2) {
                    return "";
                } else if (telType == -3) {
                    textMessage.setContent(msgTelException);
                }
                return MessageUtil.textMessageToXml(textMessage);
            }

            //判断今天是否输入过游戏名字
            if (!hasInputGameNameToday(baseMessage.getToUserName(), appKey)) {
                textMessage.setContent(getMsgTelWithoutGameName());
            } else {
                //判断微信号是否已经超过抽奖次数
                String result = wechatJoinCountToday(baseMessage.getToUserName(), appKey);
                if (StringUtils.isNotBlank(result)
                        && !isMemberTimes.equals(result)) {
                    textMessage.setContent(result);
                } else {
                    //判断手机号是否已经超过抽奖次数
                    result = telJoinCountToday(content, baseMessage.getToUserName(), appKey);
                    if (StringUtils.isNotBlank(result)) {
                        textMessage.setContent(result);
                    } else {
                        //正常参加游戏，返回游戏链接地址
                        return gameUrl();
                    }
                }
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    @Override
    protected String inputGameName() {
        if (!content.equalsIgnoreCase(getName())) {
            return "";
        }

        //判断活动是否在活动期内
        TextMessage textMessage = new TextMessage(baseMessage);
        Date now = new Date();
        if (DateTimeUtil.compareDate(getStartDate(), now) == 1) {
            textMessage.setContent(getMsgGameNotStart());
        } else if (DateTimeUtil.compareDate(getEndDate(), now) == -1) {
            textMessage.setContent(getMsgGameIsEnd());
        } else {
            //插入playgame表，准备开始游戏
            PlayGame playGame = new PlayGame();
            playGame.setAppId(appKey);
            playGame.setOpenId(baseMessage.getToUserName());
            playGame.setGameName(getNickName());
            MyRopClient.getRopClient("").buildClientRequest()
                    .post(playGame, BaseResponse.class, "playGame.insert", "1.0");

            //判断是否是新用户
            if (!isNewUser(baseMessage.getToUserName(), appKey)) {
                textMessage.setContent(msgWhenOldUser);
                return MessageUtil.textMessageToXml(textMessage);
            }

            //判断此微信号今天是否已经参加过
            String wechatJoinCountTodayResult = wechatJoinCountToday(baseMessage.getToUserName(), appKey);
            if (StringUtils.isNotBlank(wechatJoinCountTodayResult)
                    && !isMemberTimes.equals(wechatJoinCountTodayResult)) {
                textMessage.setContent(wechatJoinCountTodayResult);
            } else {
                textMessage.setContent(getMsgAfterGameName());
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    @Override
    public String wechatJoinCountToday(String openId, String appKey) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appKey);
        condition.setOpenId(openId);
        condition.setGameName(getNickName());

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getMyPrizes", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> data = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (data != null && data.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("您好，活动").append(getName()).append("仅可以参加一次~ 您的手机号码");
                    sb.append(data.get(0).get("tel").toString()).append("已获得")
                            .append(data.get(0).get("result").toString());
                    return sb.toString();
                }
                return "";
            }
        }
        return "系统繁忙，请您稍后再试";
    }

    @Override
    public String getMemberCode() {
        return null;
    }

    @Override
    public Integer getMemberStatus() {
        return null;
    }

    @Override
    public String getName() {
        return "关注有礼";
    }

    @Override
    public String getNickName() {
        return "firstFocus2";
    }

    @Override
    public String getMsgAfterGameName() {
        return "请输入呼伦贝尔移动手机号码参与活动，注意：全国家庭网用户不能参加此活动";
    }

    @Override
    public String getMsgTelNotNeiMengCMCC() {
        return "您的手机号码不是呼伦贝尔移动号码，请更换手机号码";
    }

    @Override
    public String getStartDate() {
        return "2015-02-15";
    }

    @Override
    public String getEndDate() {
        return "2015-07-01";
    }

    private boolean isNewUser(String openId, String appKey) {
        WechatUser condition = new WechatUser();
        condition.setOpenId(openId);
        condition.setAppId(appKey);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "wechatUser.listAll", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (respData != null && respData.size() == 1) {
                    Long userTime = Long.parseLong(respData.get(0).get("subscribe_time").toString());
                    Long gameTime = DateTimeUtil.getDateStartMillis(getStartDate());
                    if (userTime >= gameTime) {
                        return true;
                    }
                } else if (respData != null && respData.size() == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean endGame(String appId, String openId, String gameName, String tel, String result, String grade) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appId);
        condition.setOpenId(openId);
        condition.setGameName(gameName);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                try {
                    PlayGame playGame = new PlayGame();
                    playGame.setResult(result);
                    Integer intGrade = null;
                    if (StringUtils.isNotBlank(grade) && StringUtils.isNumeric(grade)) {
                        intGrade = Integer.parseInt(grade);
                    }
                    playGame.setPrize(intGrade);
                    playGame.setTel(tel);
                    Long finishTime = DateTimeUtil.getDateMillis(new Date());
                    playGame.setFinishTime(finishTime);

                    if (respData != null && respData.size() > 0) {
                        if (respData.get(0).get("finishTime") != null) {
                            //新增一条游戏记录
                            playGame.setAppId(appId);
                            playGame.setOpenId(openId);
                            playGame.setGameName(gameName);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                            return true;
                        } else {
                            //更新游戏的后半段
                            Long id = Long.parseLong(respData.get(0).get("id").toString());
                            playGame.setId(id);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.end", "1.0");
                            return true;
                        }
                    } else {
                        //新增一条游戏记录
                        playGame.setAppId(appId);
                        playGame.setOpenId(openId);
                        playGame.setGameName(gameName);
                        MyRopClient.getRopClient("").buildClientRequest()
                                .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
